﻿using System;
using System.Data;
using System.IO;
using System.Xml;
using Microsoft.SharePoint;
using QueryDemo.ListsSvc;

namespace QueryDemo.ResultProviders
{
	/// <summary>
	/// Uses GetListItems method on SharePoint Lists web service.
	/// </summary>
	public class ListsWebServiceResultProvider : BaseResultProvider
	{
		private XmlDocument _queryDoc;
		private Lists _listsService;
		private XmlNode _queryNode;
		private XmlNode _viewFieldsNode;
		private XmlNode _optionsNode;

		/// <summary>
		/// Sets properties related to use of the query within the web part.
		/// </summary>
		public ListsWebServiceResultProvider()
		{
			TypeOfQuery = QueryType.ListsWebService;
			QueryName = "Lists Web Service";
		}

		public override bool CrossSiteCapable
		{
			get { return false; }
		}

		public override void Init()
		{
			_listsService = new Lists
			                	{
			                		UseDefaultCredentials = true,
			                		Url = SPContext.Current.Site.Url + "/_vti_bin/Lists.asmx"
			                	};

			_queryDoc =	new XmlDocument();
			_queryNode = _queryDoc.CreateNode(XmlNodeType.Element, "Query", String.Empty);
			_viewFieldsNode = _queryDoc.CreateNode(XmlNodeType.Element, "ViewFields", String.Empty);
			_optionsNode = _queryDoc.CreateNode(XmlNodeType.Element, "QueryOptions", String.Empty);
			_queryNode.InnerXml = String.Empty;
			_viewFieldsNode.InnerXml = GetViewFieldCaml();
			_optionsNode.InnerXml = String.Empty;
		}

		public override DataTable ExecuteQuery()
		{
			XmlNode resultsNode = _listsService.GetListItems(ListTitle, null, _queryNode, _viewFieldsNode,
				RowLimit.ToString(), _optionsNode, Web.ID.ToString());
			var resultSet = new DataSet();
			resultSet.ReadXml(new StringReader(resultsNode.OuterXml));
			return resultSet.Tables["row"];
		}
	}
}
